<script setup>
import { ref, watch } from "vue";
import "@material/web/tabs/tabs";
import "@material/web/tabs/primary-tab";
import "@material/web/tabs/secondary-tab";
import TotalGraph from "@/components/graph/TotalGraph.vue";
import CategoryGraph from "@/components/graph/CategoryGraph.vue";
import { getStat } from "@/api/record";
import YearSelect from "@/components/datepicker/YearSelect.vue";

const viewType = ref("total");
const startTime = ref(null);
const endTime = ref(null);
const datesValue = ref(null);
const countsValue = ref(null);


async function getJson() {
  if (startTime.value == null || endTime.value == null) {
    return null;
  }
  const data = await getStat(startTime.value, endTime.value, "weekly");
  if (data == null) {
    return null;
  }
  console.log(data);
  return data;
}

async function getData() {
  const allData = await getJson();
  if (allData == null) {
    return null;
  }
  datesValue.value = getDates(allData);
  countsValue.value = getCounts(allData);
}

function getDates(allData) {
  const length = allData.length;
  let dates = [];
  for (let i = 0; i < length; i++) {
    dates[i] = `${allData[i].date[0]}年-第${allData[i].date[1]}周`;
  }
  console.log(dates);
  return dates;
}

function getCounts(allData) {
  const length = allData.length;
  let counts = [];
  for (let i = 0; i < length; i++) {
    counts[i] = allData[i].count;
  }
  console.log(counts);
  return counts;
}

watch(startTime, () => {
  getData();
});

watch(endTime, () => {
  getData();
});

</script>

<template>
  <div class="statistics" role="presentation">
    <Transition name="graph">
      <KeepAlive>
        <TotalGraph class="graph" v-if="viewType == 'total'" :timeType="weekly" :date="datesValue"
          :counts="countsValue">
        </TotalGraph>
      </KeepAlive>
    </Transition>
    <Transition name="graph">
      <KeepAlive>
        <CategoryGraph class="graph" v-if="viewType == 'category'" :timeType="weekly" v-model:date="datesValue"
          v-model:counts="countsValue">
        </CategoryGraph>
      </KeepAlive>
    </Transition>
    <YearSelect v-model:startYear="startTime" v-model:endYear="endTime"></YearSelect>
  </div>
</template>

<style scoped>
.statistics {
  display: grid;
  grid-template-areas: "type" "interval" "graph";
  grid-template-rows: auto auto 1fr;
  height: 100%;
}

.statistics>.type {
  grid-area: type;
}

.statistics>.interval {
  grid-area: interval;
}

.statistics>.graph {
  grid-area: graph;
}

.graph-enter-active,
.graph-leave-active {
  transition-property: opacity;
  transition-duration: var(--md-sys-motion-duration-medium2);
  transition-timing-function: linear;
}

.graph-enter-from,
.graph-leave-to {
  opacity: 0;
}
</style>